import express from "express";
import cors from "cors";
import { app } from "electron";
import path from "path";
import multer from "multer";
import { port } from "@/config/config.json"

const express_app = express();
express_app.use(cors());
const img_path = app.isPackaged
  ? path.join(process.resourcesPath, "src/assets/img/upload")
  : "src/assets/img/upload";

// 配置 multer
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, img_path);
  },
  filename: function (req, file, cb) {
    // 使用时间戳和原始文件名组合，避免文件名冲突
    const unique_suffix = Date.now() + "-" + Math.round(Math.random() * 1e9);
    // 提取文件扩展名
    const extname = path.extname(file.originalname);
    // 使用唯一后缀和文件扩展名组合新文件名
    cb(null, unique_suffix + extname);
  },
});

const upload = multer({ storage: storage });

express_app.use("/img", express.static(img_path));

// 图片上传接口
express_app.post("/upload-image", upload.single("image"), (req, res) => {
  if (!req.file) {
    return res.status(400).send("No image uploaded");
  }

  // 返回图片的访问路径
  const imagePath = `/img/${path.relative(img_path, req.file.path)}`;

  res.json({
    success: true,
    imagePath: imagePath,
  });
});

// 代理路由
express_app.get("/proxy-image", async (req, res) => {
  const imageUrl = req.query.url;
  if (!imageUrl) {
    return res.status(400).send("URL is required");
  }

  try {
    const response = await fetch(imageUrl);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const contentType = response.headers.get("content-type") || "image/jpeg";
    const buffer = await response.arrayBuffer(); // 读取为 ArrayBuffer
    const dataBuffer = Buffer.from(buffer); // 转换为 Buffer
    const base64Data = dataBuffer.toString("base64"); // 转换为 Base64 字符串

    res.json({
      contentType,
      data: base64Data,
    });
  } catch (error) {
    console.error("Error fetching image:", error);
    res.status(500).send("Error fetching image");
  }
});

export { express_app, port };
// 启动服务器
// express_app.listen(PORT, () => {
//   console.log(`Proxy server is running on http://localhost:${PORT}`);
// });
